<template>
  <div>
    <!--上传组件-->
    <!--  <el-upload
      class="upload-demo"
      :action="uploadUrl"  // 上传地址
      :auto-upload="false"  // 禁用自动上传
      :on-change="handleChange"  // 文件选择时触发
      :before-upload="handleBeforeUpload"  // 文件上传前触发
      :on-progress="handleProgress"  // 上传进度变化时触发
    > -->
    <el-upload
      class="upload-demo"
      :action="uploadUrl"
      :auto-upload="false"
      :on-change="handleChange"
      :before-upload="handleBeforeUpload"
      :on-progress="handleProgress"
    >
      <el-button slot="trigger">选取文件</el-button> // 选择文件按钮
      <!--上传文件按钮-->
      <el-button
        style="margin-left: 10px"
        type="primary"
        :loading="uploading"
        :disabled="files.length === 0"
        @click="handleUpload"
      >
        上传文件
      </el-button>
      <div class="clearfix"></div>
      <el-progress :percentage="percent"></el-progress> // 上传进度条
    </el-upload>
  </div>
</template>

<script>
import axios from "axios";
import { ElMessage } from "element-ui"; // 引入Element UI库中的消息提示组件

export default {
  data() {
    return {
      files: [], // 选中的文件列表
      uploading: false, // 是否正在上传
      percent: 0, // 上传进度
      uploadUrl: "https://your.upload.url", // 上传地址
    };
  },
  methods: {
    // 切片上传
    async upload(file) {
      const chunkSize = 1024 * 1024; // 每个块的大小为 1MB
      const fileSize = file.size; // 文件大小
      const chunks = Math.ceil(fileSize / chunkSize); // 总块数
      const tasks = []; // 上传任务数组
      let uploaded = 0; // 已上传块数
      // 文件切割
      for (let i = 0; i < chunks; i++) {
        const start = i * chunkSize;
        const end = Math.min(start + chunkSize, fileSize);

        tasks.push(
          new Promise((resolve, reject) => {
            const formData = new FormData();
            formData.append("chunk_index", i); // 块编号
            formData.append("chunk_count", chunks); // 总块数
            formData.append("file_id", file.id); // 文件ID
            formData.append("chunk_data", file.slice(start, end)); // 块数据
            axios
              .post(this.uploadUrl, formData) // 上传块数据
              .then(res => {
                uploaded++;
                this.percent = Math.floor((uploaded / chunks) * 100);
                resolve();
              })
              .catch(err => {
                reject(err);
              });
          })
        );
      }

      // 待所有块上传完成后，发送合并请求
      await Promise.all(tasks);
      const res = await axios.post(this.uploadUrl, {
        file_id: file.id,
        chunks,
      });

      // 上传成功，返回文件URL
      if (res.status === 200) {
        return `${this.uploadUrl}/${file.id}`;
      } else {
        throw new Error(res.data.message);
      }
    },
    handleChange(files) {
      this.files = files;
    },
    async handleUpload() {
      try {
        this.uploading = true;
        for (let i = 0; i < this.files.length; i++) {
          const file = this.files[i];
          const url = await this.upload(file);
          // 文件上传成功，将url展示给用户
          ElMessage.success(`文件${file.name}上传成功！URL：${url}`);
        }
      } catch (err) {
        ElMessage.error(`文件上传失败！${err.message}`);
      } finally {
        this.uploading = false;
      }
    },
    handleBeforeUpload() {
      // TODO: 检查文件大小、类型等
    },
    handleProgress(event, file) {
      // 显示上传进度
      this.percent = Math.floor((event.loaded / event.total) * 100);
    },
  },
};
</script>
